<template>
  <div>
    <van-nav-bar
  title="商品搜索"
  left-arrow
  @click-left="$router.back()"
   class="custom-navbar"
/>
  <van-search
  v-model="value"
  show-action
  placeholder="请输入搜索关键词"
  @search="onSearch"
>
  <template #action>
    <div @click="onSearch(value)">搜索</div>
  </template>
</van-search>
  <div class="mid">
    <span>最近搜索</span>
    <van-icon name="delete-o" @click="clear" />
  </div>
  <div class="results" v-if="results.length>0">
    <div class="result" v-for="(item,index) in results" :key="index" @click="onSearch(item)">{{ item }}</div>
  </div>
  </div>
</template>
<script>
import { Dialog } from 'vant'
import { getHistory, setHistory, clearHistory } from '@/utils/storage'
export default {
  name: 'searchIndex',
  data () {
    return {
      value: '',
      results: getHistory()
    }
  },
  methods: {
    onSearch (key) {
      if (key.trim() === '') {
        Dialog.alert({
          title: '搜索内容不能为空！'
        })
        return
      }
      const index = this.results.indexOf(key)
      if (index !== -1) {
        this.results.splice(index, 1)
      }
      this.results = [...new Set([...this.results, key])]
      setHistory(this.results)
      this.$router.push('/searchList?key=' + key)
      this.value = ''
    },
    clear () {
      Dialog.confirm({
        title: '确认清空搜索历史吗？'
      })
        .then(() => {
          // on confirm
          this.results = []
          clearHistory()
        })
        .catch(() => {
          // on cancel
        })
    }
  }
}
</script>
<style>
.custom-navbar {
  /* background-color: #4CAF50; 设置背景颜色 */
  color: white; /* 设置文字颜色 */
  font-size: 18px; /* 调整字体大小 */
}

.custom-navbar .van-nav-bar__title {
  font-weight: bold; /* 设置标题加粗 */
}

.custom-navbar .van-nav-bar__left {
  color: white; /* 设置返回箭头颜色 */
}
.mid{
  display: flex;
  justify-content: space-between;
  font-size: 20px;
  padding-left: 10px;
}
.results{
  margin: 10px;
  display: grid;                   /* 使用 CSS Grid 布局 */
  grid-template-columns: repeat(4, 1fr);  /* 每行显示 3 个项 */
  gap: 10px;                       /* 每个项之间的间距 */
  margin-top: 20px;                 /* 搜索历史与搜索框之间的间距 */
}
.result{
  width: 70px;
  height: 30px;
  background-color: #f2f2f2;
  border-radius: 15px;
  text-align: center;
  line-height: 30px;
  cursor: pointer;
}
</style>
